package com.wy.panda.manager.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.wy.panda.common.util.CollectionUtils;
import com.wy.panda.dao.mapper.SysDictMapper;
import com.wy.panda.entity.SysDictEntity;
import com.wy.panda.manager.SysDictManager;

@Component
@CacheConfig(cacheNames = {"SysDictEntity"})
public class SysDictManagerImpl implements SysDictManager {
    
    @Autowired
    private SysDictMapper sysDictMapper;
    
    @Autowired
    private CacheManager cacheManager;
    
    private Cache cache;
    
    @PostConstruct
    public void init() {
        cache = cacheManager.getCache(SysDictEntity.class.getSimpleName());
    }
    
    @Cacheable
    @Override
    public SysDictEntity getById(Serializable id) {
        return sysDictMapper.selectById(id);
    }

    @Override
    public List<SysDictEntity> listByIds(Collection<? extends Serializable> idList) {
        if(CollectionUtils.isEmpty(idList)) {
            return Collections.emptyList();
        }
        
        List<SysDictEntity> result = Lists.newArrayList();
        List<Serializable> notHitCacheIdList = Lists.newArrayList();
        idList.forEach(idItem -> {
            SysDictEntity t = null;
            ValueWrapper valueWrapper = cache.get(idItem);
            if(valueWrapper != null) {
                t = (SysDictEntity) valueWrapper.get();
            } else {
                notHitCacheIdList.add(idItem);
            }
            
            if(t != null) {
                result.add(t);
            }
        });
        
        if(CollectionUtils.isEmpty(notHitCacheIdList)) {
            return result;
        }
        
        List<SysDictEntity> list = sysDictMapper.selectBatchIds(notHitCacheIdList);
        if(list == null) {
            list = Collections.emptyList();
        }
        
        list.forEach(item -> {
            cache.put(item.getId(), item);
            
            notHitCacheIdList.remove(item.getId());
        });
        
        notHitCacheIdList.forEach(idItem -> {
            cache.put(idItem, null);
        });
        
        //合并未缓存命中的记录
        result.addAll(list);
        
        return result;
    }
}
